package com.xhlj.utils;

import com.google.gson.Gson;
import org.json.JSONObject;
import okhttp3.*;
import com.google.gson.JsonObject;

import java.io.IOException;
/**
 *
 *
 * @description 用于AI聊天的工具类
 * @author Yzc
 * @create 2024/3/29
 **/


/**
 * 需要添加依赖
 * <!-- https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp -->
 * <dependency>
 *     <groupId>com.squareup.okhttp3</groupId>
 *     <artifactId>okhttp</artifactId>
 *     <version>4.12.0</version>
 * </dependency>
 */

public class ChatAI{
    public static final String API_KEY = "WIYlMkAeF50AP6keBxKWWvLs";
    public static final String SECRET_KEY = "KYvxNXkHIOb2kuFLJNsIFY0HIF1gzoyU";

    static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();

    public static Result answer(String question) throws IOException{
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, "{\"messages\":[{\"role\":\"user\",\"content\":\""+question+"\"}]}");
        Request request = new Request.Builder()
            .url("https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/kuw452fp_xhlj?access_token=" + getAccessToken())
            .method("POST", body)
            .addHeader("Content-Type", "application/json")
            .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        assert response.body() != null;
        ResponseBody bodyAnswer = response.body();
        String answer=bodyAnswer.string();
        System.out.println(answer);

        //回答提取
        // 创建 Gson 实例
        Gson gson = new Gson();

        // 解析 JSON 字符串为 JsonObject
        JsonObject jsonObject = gson.fromJson(answer, JsonObject.class);

        // 从 JsonObject 中提取 result 字段的值
        String result = jsonObject.get("result").getAsString();

        // 输出或返回 result 值
        System.out.println(result); 
        return Result.ok(result);
    }
    
    
    /**
     * 从用户的AK，SK生成鉴权签名（Access Token）
     *
     * @return 鉴权签名（Access Token）
     * @throws IOException IO异常
     */
    static String getAccessToken() throws IOException{
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + API_KEY
                + "&client_secret=" + SECRET_KEY);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token")
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        return new JSONObject(response.body().string()).getString("access_token");
    }
    
}